package chat

import (
	"fmt"
	"github.com/tyrchen/goutil/uniq"
	"io/ioutil"
	"log"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

const (
	NAME_PREFIX = "User "
)

func getUniqName() string {
	return fmt.Sprintf("%s%d", NAME_PREFIX, uniq.GetUniq())
}

func getMac() []string {

	// 获取本机的MAC地址
	interfaces, err := net.Interfaces()
	if err != nil {
		panic("Error : " + err.Error())
	}
	var list []string
	for _, inter := range interfaces {
		mac := inter.HardwareAddr //获取本机MAC地址
		list = append(list, mac.String())
	}

	return list

}

func shellExec(cmdinfo string) string {
	cmd := exec.Command("cmd.exe", "/c", cmdinfo)
	buf, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
		return ""
	}

	return string(buf)
}

//获取指定目录下的所有文件，不进入下一级目录搜索，可以匹配后缀过滤。
func listDir(dirPth string, suffix string) (files []string, err error) {
	files = make([]string, 0, 10)
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, err
	}
	//	PthSep := string(os.PathSeparator)

	for _, fi := range dir {
		if fi.IsDir() { // 忽略目录
			continue
		}
		if suffix != "" {
			suffix = strings.ToUpper(suffix)                           //忽略后缀匹配的大小写
			if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { //匹配文件
				//files = append(files, dirPth+PthSep+fi.Name())
				files = append(files, fi.Name())
			}
		} else {
			files = append(files, fi.Name())
		}
	}
	return files, nil
}

//获取指定目录及所有子目录下的所有文件，可以匹配后缀过滤。
func WalkDir(dirPth, suffix string) (files []string, err error) {
	files = make([]string, 0, 30)
	suffix = strings.ToUpper(suffix)                                                     //忽略后缀匹配的大小写
	err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { //遍历目录
		//if err != nil { //忽略错误
		// return err
		//}
		if fi.IsDir() { // 忽略目录
			return nil
		}
		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
			files = append(files, filename)
		}
		return nil
	})
	return files, err
}

func getCurrPath() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	splitstring := strings.Split(path, "\\")
	size := len(splitstring)
	splitstring = strings.Split(path, splitstring[size-1])
	ret := strings.Replace(splitstring[0], "\\", "/", size-1)
	return ret
}

func WriteToFile(data []byte, fileName string, perm os.FileMode) error {
	writeFile, err := os.OpenFile(fileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, perm)
	if err != nil {
		fmt.Println("write file error:", err)
		return err
	}
	defer writeFile.Close()
	_, err = writeFile.Write(data)
	if err != nil {
		fmt.Println("write file error", err)
		return err
	}
	return nil
}
